package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.Constant;
import com.example.demo.model.entity.BalanceModel;
import com.example.demo.model.entity.ProductModel;
import com.example.demo.model.entity.UserModel;
import com.example.demo.service.impl.BalanceService;
import com.example.demo.service.impl.ProductService;
import com.example.demo.service.impl.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.persistence.criteria.*;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping(value = Constant.API_VERSION + "/product")
public class ProductController {

    @Autowired
    UserService userService;

    @Autowired
    ProductService productService;

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public ProductModel add(@RequestHeader("Authorization") String token, @RequestBody ProductModel model) throws Exception {
        BASE64Decoder decoder = new BASE64Decoder();
        String currentUid = new String(decoder.decodeBuffer(token), "UTF-8");
        UserModel user = userService.getByUid(currentUid);
        if (user.getRole() == Constant.Role.USER.getRoleCode()) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 403, "权限不足"));
        }
        model.setProductId(UUID.randomUUID().toString());
        model.setCreateTime(System.currentTimeMillis());
        return productService.save(model);

    }


    @RequestMapping(value = "/{product_id}", method = RequestMethod.DELETE)
    @ResponseBody
    public void add(@RequestHeader("Authorization") String token, @PathVariable(value = "product_id") String productId) throws Exception {
        BASE64Decoder decoder = new BASE64Decoder();
        String currentUid = new String(decoder.decodeBuffer(token), "UTF-8");
        UserModel user = userService.getByUid(currentUid);
        if (user.getRole() == Constant.Role.USER.getRoleCode()) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 403, "权限不足"));
        }
        productService.delete(productId);

    }


    @RequestMapping(value = "/{product_id}", method = RequestMethod.GET)
    @ResponseBody
    public ProductModel get(@RequestHeader("Authorization") String token, @PathVariable(value = "product_id") String productId) throws Exception {
        BASE64Decoder decoder = new BASE64Decoder();
        String currentUid = new String(decoder.decodeBuffer(token), "UTF-8");
        UserModel user = userService.getByUid(currentUid);
        if (user.getRole() == Constant.Role.USER.getRoleCode()) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 403, "权限不足"));
        }
        ProductModel productModel = productService.getById(productId);
        if (productModel == null) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 400, "商品不存在"));
        }
        return productModel;
    }

    @RequestMapping(value = "/{qrcode}/action/scan", method = RequestMethod.GET)
    @ResponseBody
    public ProductModel get(@PathVariable(value = "qrcode") String qrcode) throws Exception {
        ProductModel productModel = productService.getByQrcode(qrcode);
        if (productModel == null) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 400, "商品不存在"));
        }
        return productModel;
    }


    @RequestMapping(value = "/{product_id}", method = RequestMethod.PUT)
    @ResponseBody
    public ProductModel update(@RequestHeader("Authorization") String token, @PathVariable(value = "product_id") String productId, @RequestBody ProductModel model) throws Exception {
        BASE64Decoder decoder = new BASE64Decoder();
        String currentUid = new String(decoder.decodeBuffer(token), "UTF-8");
        UserModel user = userService.getByUid(currentUid);
        if (user.getRole() == Constant.Role.USER.getRoleCode()) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 403, "权限不足"));
        }
        ProductModel productModel = productService.getById(productId);
        if (productModel == null) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 400, "商品不存在"));
        }
        if (StringUtils.isNotEmpty(model.getProductName())) {
            productModel.setProductName(model.getProductName());
        }
        if (StringUtils.isNotEmpty(model.getProductDesc())) {
            productModel.setProductDesc(model.getProductDesc());
        }
        if (StringUtils.isNotEmpty(model.getProductImg())) {
            productModel.setProductImg(model.getProductImg());
        }
        if (StringUtils.isNotEmpty(model.getCategoryId())) {
            productModel.setProductImg(model.getCategoryId());
        }
        if (model.getPrice() != null) {
            productModel.setPrice(model.getPrice());
        }
        if (model.getTotalCount() != null) {
            productModel.setTotalCount(model.getTotalCount());
        }
        return productService.save(productModel);

    }


    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getProductList(@RequestParam(value = "page_size", defaultValue = "10") String pageSize,
                                     @RequestParam(value = "page_number", defaultValue = "1") String pageNumber,
                                     @RequestParam(value = "category_id", defaultValue = "") final String categoryId) throws Exception {

        Page<ProductModel> productPage = productService.getProductPage(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(categoryId)) {
                    Path<String> categoryPath = root.get("categoryId");
                    predicateList.add(criteriaBuilder.equal(categoryPath, categoryId));
                }
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        }, new PageRequest(Integer.valueOf(pageNumber) - 1, Integer.valueOf(pageSize)));

        JSONObject result = new JSONObject();
        result.put("total", productPage.getTotalElements());
        result.put("items", productPage.getContent());
        return result;
    }


}
